package com.codedancer.campus.client.service.impl;

import com.codedancer.campus.client.service.ICommonService;
import com.codedancer.campus.common.exception.BusinessException;
import com.codedancer.campus.common.utils.TencentCOS;
import java.io.File;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class CommonServiceImpl implements ICommonService {


    /**
     * 上传图片
     * @param image 要上传的图片
     * @return
     */
    @Override
    public String uploadImage(MultipartFile image) {
        log.info("开始上传图片");
        //获取图片的名称
        String imageName = image.getOriginalFilename();
        //判断有无后缀
        assert imageName != null;
        if (imageName.lastIndexOf(".") < 0) {
            throw new BusinessException("图片格式错误");
        }
        //获取文件后缀
        String prefix = imageName.substring(imageName.lastIndexOf("."));
        //如果不是图片
        if (!prefix.equalsIgnoreCase(".jpg") && !prefix.equalsIgnoreCase(".jpeg") && !prefix
            .equalsIgnoreCase(".svg") && !prefix.equalsIgnoreCase(".gif") && !prefix
            .equalsIgnoreCase(".png")) {
            throw new BusinessException("只支持图片格式");
        }
        try {
            //使用uuid作为文件名，防止生成的临时文件重复
            final File excelFile = File
                .createTempFile("imagesFile-" + System.currentTimeMillis(), prefix);
            //将Multifile转换成File
            image.transferTo(excelFile);
            // 调用上传工具类
            Map<String, String> map = TencentCOS.uploadImage(excelFile);
            assert map != null;
            log.info("图片上传完成");
            log.info("图片地址：{}",map.get("url"));
            return map.get("url");
        } catch (Exception e) {
            e.fillInStackTrace();
            throw new BusinessException("系统错误");
        }
    }
}
